<?php
class FrontController {
    
    static function dispatch( Router $r ) {
        $params = $r -> getUriParams();
        
        $controller = self::getControllerName( $r, strtolower( $params[ 'controller_name' ] ) );
        include CONTROLLERS_PATH . $controller . PHP_EX ;
        $controller .= '_Controller';
        $controller = new $controller();
        if( !( $controller instanceof Controller ) ) {
            unset( $controller );
            throw new FrameException( 'Kontroler musi pochodzić od głównego kontrolera' );
        }
        
        $method = self::getControllerMethod( $r, $controller, $params[ 'controller_method' ]);
        $controller -> $method();
        exit;
    }
    
    static private function getControllerName( Router $r, $name ) {
        if( $name ) {
            if( file_exists( CONTROLLERS_PATH . $name . PHP_EX ) )
                return ucfirst( $name );
            else
                $r -> error404();
        }
        $default = strtolower( Config::get( 'default_controller', 'config' ) );
        if( file_exists( CONTROLLERS_PATH . $default . PHP_EX ) )
            return ucfirst( $default );
        else
            throw new FrameException( 'Brak domyślnego kontrolera!' );
    }
    static private function getControllerMethod( Router $r, Controller $controller, $method ) {
        if( $method ) {
            $method = strtolower( $method );
            if( !method_exists($controller, $method) )
                $r -> error404();
        }else {
            $method = strtolower( Config::get( 'default_controller_method', 'config' ) );
            if( !method_exists($controller, $method) )
                throw new FrameException( 'Kontroler nie jest poprawny' );
        }
        return $method;
    }
}